package com.codeant.bikeindicatorapplication;

import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import com.codeant.bikeindicatorapplication.tools.ClickFeedbackHelper;
import com.codeant.bikeindicatorapplication.tools.SingleToast;
import com.qmuiteam.qmui.skin.QMUISkinManager;
import com.qmuiteam.qmui.util.QMUIDisplayHelper;
import com.qmuiteam.qmui.widget.popup.QMUIPopup;
import com.qmuiteam.qmui.widget.popup.QMUIPopups;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Set;
import java.util.UUID;

//仅在设置界面调试蓝牙用，可直接删除
public class BleDebugActivity extends Activity {
    private String TAG = "BleDebugActivity";

//    private final String DEVICE_ADDRESS="98:D3:31:FD:BE:80";
    private final UUID PORT_UUID = UUID.fromString("00001101-0000-1000-8000-00805f9b34fb");//蓝牙串口服务
    private BluetoothDevice device;
    private BluetoothSocket socket=null;
    private OutputStream outputStream=null;
    private InputStream inputStream=null;

    Button startBtn,sendBtn,clearBtn,stopBtn,quitBtn;
    TextView orderTv;
    EditText orderEt;

    BluetoothAdapter bleAdapter;//系统蓝牙适配器

    boolean deviceConnected=false;
    Thread thread;
    byte buffer[];
    int bufferPosition;
    boolean stopThread;

    private Integer TAG_BTN_START = 1;
    private Integer TAG_BTN_SEND = 2;
    private Integer TAG_BTN_STOP = 3;
    private Integer TAG_BTN_CLEAR = 4;
    private Integer TAG_BTN_QUIT = 5;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_ble_debug);
        
        initWidgets();
    }
    
    public void initWidgets(){
        startBtn = (Button) findViewById(R.id.buttonStart);
        sendBtn = (Button) findViewById(R.id.buttonSend);
        clearBtn = (Button) findViewById(R.id.buttonClear);
        stopBtn = (Button) findViewById(R.id.buttonStop);
        quitBtn = (Button) findViewById(R.id.buttonQuit);
        orderEt = (EditText) findViewById(R.id.editText);
        orderTv = (TextView) findViewById(R.id.textviewOrder);

        startBtn.setOnClickListener(new ClickListeners());
        startBtn.setTag(TAG_BTN_START);

        sendBtn.setOnClickListener(new ClickListeners());
        sendBtn.setTag(TAG_BTN_SEND);

        clearBtn.setOnClickListener(new ClickListeners());
        clearBtn.setTag(TAG_BTN_CLEAR);

        stopBtn.setOnClickListener(new ClickListeners());
        stopBtn.setTag(TAG_BTN_STOP);

        quitBtn.setOnClickListener(new ClickListeners());
        quitBtn.setTag(TAG_BTN_QUIT);

        setUiEnabled(false);

        bleAdapter = BluetoothAdapter.getDefaultAdapter();
    }

    //设置四个按钮的状态
    public void setUiEnabled(boolean bool) {
        startBtn.setEnabled(!bool);
        sendBtn.setEnabled(bool);
        stopBtn.setEnabled(bool);
        orderTv.setEnabled(bool);

    }

    //初始化蓝牙适配器等
    public boolean BTinit(String DEVICE_ADDRESS) {
        boolean found=false;
        BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
        if (bluetoothAdapter == null) {
            SingleToast.getInstance(BleDebugActivity.this).show("此设备不支持蓝牙");
        }
        if(!bluetoothAdapter.isEnabled()) {
            Intent enableAdapter = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
            startActivityForResult(enableAdapter, 0);
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        Set<BluetoothDevice> bondedDevices = bluetoothAdapter.getBondedDevices();
        if(bondedDevices.isEmpty()) {
            SingleToast.getInstance(BleDebugActivity.this).show("无配对设备，请先配对");
        } else {
            for (BluetoothDevice iterator : bondedDevices) {
                //根据选择的mac来连接设备
                if(iterator.getAddress().equals(DEVICE_ADDRESS)) {
                    device=iterator;
                    found=true;
                    break;
                }
            }
        }
        return found;
    }

    //连接蓝牙
    public boolean BTconnect() {
        boolean connected=true;
        try {
            socket = device.createRfcommSocketToServiceRecord(PORT_UUID);
            socket.connect();
        } catch (IOException e) {
            e.printStackTrace();
            connected=false;
        }
        if(connected) {
            try {
                outputStream=socket.getOutputStream();
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                inputStream=socket.getInputStream();
            } catch (IOException e) {
                e.printStackTrace();
            }

        }

        return connected;
    }

    //连接设备part2（HC05）-监听数据流
    public void beginListenForData() {
        final Handler handler = new Handler();
        stopThread = false;
        buffer = new byte[1024];
        Thread thread  = new Thread(new Runnable() {
            public void run() {
                while(!Thread.currentThread().isInterrupted() && !stopThread) {
                    try {
                        int byteCount = inputStream.available();
                        if(byteCount > 0) {
                            byte[] rawBytes = new byte[byteCount];
                            inputStream.read(rawBytes);
                            final String string=new String(rawBytes,"UTF-8");
                            handler.post(new Runnable() {
                                public void run() {
                                    orderTv.append(string);
                                }
                            });

                        }
                    }
                    catch (IOException ex) {
                        stopThread = true;
                    }
                }
            }
        });

        thread.start();
    }

    private class ClickListeners implements View.OnClickListener {
        public void onClick(View view) {
            new ClickFeedbackHelper().feedback(view, BleDebugActivity.this);

            int key = 0;
            if (view.getTag() != null) {
                key = (Integer) view.getTag();
            }
            switch (key) {
                case 1://连接,连接设备part1（HC05）
                    // 1.绑定已配对设备数据
                    Set<BluetoothDevice> devices = bleAdapter.getBondedDevices();
                    List<BluetoothDevice> devices_list = new ArrayList<>(devices);
                    ArrayList<String> listItems = new ArrayList<>();
                    String[] listItems_1;
                    for(BluetoothDevice device:devices){
                        listItems.add(device.getName());
                    }
                    listItems_1 = new String[listItems.size()];
                    listItems.toArray(listItems_1);
                    List<String> data = new ArrayList<>();
                    Collections.addAll(data, listItems_1);
                    ArrayAdapter<String> adapter = new ArrayAdapter<String>(
                            BleDebugActivity.this,
                            R.layout.simple_list_item,
                            data);

                    // 2.弹框的生成
                    QMUIPopups.listPopup(BleDebugActivity.this,
                            QMUIDisplayHelper.dp2px(BleDebugActivity.this, 250),
                            QMUIDisplayHelper.dp2px(BleDebugActivity.this, 300),
                            adapter,
                            new AdapterView.OnItemClickListener() {
                                @Override
                                public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                                    //让所有可点击事件都带有震动反馈（线性马达或者普通震动）
                                    new ClickFeedbackHelper().feedback(view, BleDebugActivity.this);
                                    SingleToast.getInstance(BleDebugActivity.this).show("连接"+devices_list.get(position).getName()+"中");
                                    if(BTinit(devices_list.get(position).getAddress())) {
                                        if(BTconnect()) {
                                            setUiEnabled(true);
                                            deviceConnected=true;
                                            beginListenForData();
                                            orderTv.append("\nConnection Opened!\n");
                                        }
                                    }
                                }
                            })
                            .animStyle(QMUIPopup.ANIM_GROW_FROM_CENTER)
                            .preferredDirection(QMUIPopup.DIRECTION_TOP)
                            .shadow(true)
                            .arrow(true)
                            .dimAmount(0.6f)
                            .shadowElevation(10,5)
                            .edgeProtection(QMUIDisplayHelper.dp2px(BleDebugActivity.this, 10))
                            .offsetYIfTop(QMUIDisplayHelper.dp2px(BleDebugActivity.this, 5))
                            .skinManager(QMUISkinManager.defaultInstance(BleDebugActivity.this))
                            .show(view);
                    Log.d(TAG, "连接");
                    break;
                case 2://发送
                    String string = orderEt.getText().toString();
                    string.concat("\n");
                    try {
                        outputStream.flush();
                        outputStream.write(string.getBytes());
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                    orderTv.append("\nSent Data:"+string+"\n");
                    Log.d(TAG, "发送");
                    break;
                case 3://断开
                    stopThread = true;
                    try {
                        if (inputStream!=null){
                            inputStream.close();
                        }
                        if (outputStream!=null){
                            outputStream.close();
                        }
                        if (socket!=null){
                            socket.close();
                        }
                        setUiEnabled(false);
                        deviceConnected=false;
                        orderTv.append("\nConnection Closed!\n");
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                    Log.d(TAG, "断开");
                    break;
                case 4://清空（文本框）
                    orderEt.setText("");
                    orderTv.setText("");
                    Log.d(TAG, "清空");
                    break;
                case 5://退出
                    //关闭输入输出流
                    try {
                        if (outputStream!=null || inputStream!=null){
                            outputStream.close();
                            inputStream.close();
                        }
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                    finish();
                    Log.d(TAG, "退出");
                    break;
                default:
                    break;
            }
        }
    }
}

